import { useState, useEffect } from 'react';

import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { ComprehensiveScore, mockScores } from '../mock/comprehensiveScoreData';
import { Student, mockStudents } from '../mock/studentData';

export default function ComprehensiveScoreManagementPage() {
  const { session } = useSession();
  const [scores, setScores] = useState<ComprehensiveScore[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentScore, setCurrentScore] = useState<ComprehensiveScore | null>(null);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [form, setForm] = useState({
    studentId: '',
    studentName: '',
    semester: '',
    bonusScore: '',
    bonusReason: '',
    penaltyScore: '',
    penaltyReason: '',
    updateDate: new Date().toISOString().split('T')[0],
  });
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedSemester, setSelectedSemester] = useState('all');

  // 学期选项
  const semesters = ['all', '2023-2024第一学期', '2023-2024第二学期', '2024-2025第一学期'];
  
  // 评价等级选项
  const evaluations = ['优秀', '良好', '中等', '及格', '不及格'];

  // 权限检查
  const canEdit = session?.userRole === 'admin' || session?.userRole === 'user';
  const canDelete = session?.userRole === 'admin';
  const canAdd = session?.userRole === 'admin' || session?.userRole === 'user';

  useEffect(() => {
    loadScores();
  }, []);

  // 加载综合积分数据
  const loadScores = async () => {
    setLoading(true);
    try {
      // 从localStorage获取数据或使用mock数据
      const savedScores = localStorage.getItem('comprehensiveScores');
      if (savedScores) {
        const parsedScores = JSON.parse(savedScores);
        // 与学生数据同步
        const scoresWithUpdatedData = syncScoresWithStudents(parsedScores);
        setScores(scoresWithUpdatedData);
      } else {
        // 使用mock数据并与学生数据同步
        const syncedMockScores = syncScoresWithStudents(mockScores);
        setScores(syncedMockScores);
        localStorage.setItem('comprehensiveScores', JSON.stringify(syncedMockScores));
      }
    } catch (error) {
      console.error('加载综合积分数据失败:', error);
      // 即使出错也尝试与学生数据同步
      const syncedMockScores = syncScoresWithStudents(mockScores);
      setScores(syncedMockScores);
    } finally {
      setLoading(false);
    }
  };

  // 与学生数据同步综合积分
  const syncScoresWithStudents = (scores: ComprehensiveScore[]): ComprehensiveScore[] => {
    // 确保学生数据已加载
    const students = JSON.parse(localStorage.getItem('students') || JSON.stringify(mockStudents));
    
    return scores.map(score => {
      // 查找对应的学生
      const student = students.find((s: Student) => s.studentId === score.studentId);
      
      if (student) {
        // 更新学生姓名以确保与studentData一致
        const updatedScore = { ...score, studentName: student.name };
        
        // 检查学生数据中的score字段，如果存在则同步
        if (student.score && !isNaN(parseFloat(student.score))) {
          updatedScore.totalScore = parseFloat(student.score);
          // 根据总积分重新计算评价
          updatedScore.evaluation = calculateEvaluation(parseFloat(student.score));
        } else {
          // 根据加分减分计算总积分
          const baseScore = 80; // 默认基础分为80分
          const totalScore = baseScore + (score.bonusScore || 0) - (score.penaltyScore || 0);
          updatedScore.totalScore = totalScore;
          // 计算评价
          updatedScore.evaluation = calculateEvaluation(totalScore);
          
          // 同时更新学生数据中的score字段
          const updatedStudents = students.map((s: Student) => 
            s.studentId === score.studentId ? { ...s, score: totalScore.toString() } : s
          );
          localStorage.setItem('students', JSON.stringify(updatedStudents));
        }
        
        return updatedScore;
      }
      
      return score;
    });
  };

  // 计算评价等级
  const calculateEvaluation = (totalScore: number): string => {
    if (totalScore >= 90) {
      return '优秀';
    } else if (totalScore >= 80) {
      return '良好';
    } else if (totalScore >= 70) {
      return '中等';
    } else if (totalScore >= 60) {
      return '及格';
    } else {
      return '不及格';
    }
  };

  // 计算总积分
  const calculateTotalScore = (scores: Record<string, string>): number => {
    // 默认基础分为80分，加上加分项，减去减分项
    const baseScore = 80;
    const bonusScore = parseFloat(scores.bonusScore || '0');
    const penaltyScore = parseFloat(scores.penaltyScore || '0');
    
    const totalScore = Math.max(0, Math.min(100, baseScore + bonusScore - penaltyScore));
    return Math.round(totalScore * 100) / 100;
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: ['academicScore', 'behaviorScore', 'activityScore', 'bonusScore', 'penaltyScore'].includes(name) 
        ? parseFloat(value) || 0 
        : value
    }));
  };



  // 打开添加对话框
  const handleAddOpen = () => {
    resetForm();
    setIsAddOpen(true);
  };

  // 打开编辑对话框
  const handleEditOpen = (score: ComprehensiveScore) => {
    setCurrentScore(score);
    setForm({
      studentId: score.studentId,
      studentName: score.studentName,
      semester: score.semester,
      bonusScore: score.bonusScore,
      bonusReason: score.bonusReason || '',
      penaltyScore: score.penaltyScore,
      penaltyReason: score.penaltyReason || '',
      updateDate: score.updateDate,
    });
    setIsEditOpen(true);
  };

  // 打开删除对话框
  const handleDeleteOpen = (score: ComprehensiveScore) => {
    setCurrentScore(score);
    setIsDeleteOpen(true);
  };

  // 处理添加综合积分
  const handleAdd = async () => {
    try {
      setLoading(true);
      
      // 计算总积分
      const totalScore = calculateTotalScore(form);
      // 计算评价等级
      const evaluation = calculateEvaluation(totalScore);
      
      // 创建新的积分记录
      const newScore: Omit<ComprehensiveScore, 'id'> = {
        studentId: form.studentId,
        studentName: form.studentName,
        semester: form.semester,
        baseScore: 80, // 默认基础分
        bonusScore: parseFloat(form.bonusScore || '0'),
        bonusReason: form.bonusReason || '',
        penaltyScore: parseFloat(form.penaltyScore || '0'),
        penaltyReason: form.penaltyReason || '',
        totalScore,
        evaluation,
        updateDate: form.updateDate
      };
      
      // 保存到localStorage
      const savedScores = JSON.parse(localStorage.getItem('comprehensiveScores') || '[]');
      const newScoreWithId = {
        ...newScore,
        id: savedScores.length > 0 ? Math.max(...savedScores.map((s: any) => s.id)) + 1 : 1
      };
      const updatedScores = [...savedScores, newScoreWithId];
      localStorage.setItem('comprehensiveScores', JSON.stringify(updatedScores));
      
      // 更新学生数据中的score字段以保持同步
      const students = JSON.parse(localStorage.getItem('students') || JSON.stringify(mockStudents));
      const updatedStudents = students.map((s: Student) => 
        s.studentId === form.studentId ? { ...s, score: totalScore.toString() } : s
      );
      localStorage.setItem('students', JSON.stringify(updatedStudents));
      
      // 重新加载数据以更新UI
      await loadScores();
      setIsAddOpen(false);
      setAlert('添加综合积分成功');
      setShowAlert(true);
      
      // 重置表单
      resetForm();
    } catch (error) {
      console.error('添加综合积分失败:', error);
      setAlert('添加综合积分失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 处理编辑综合积分
  const handleEdit = async () => {
    if (!currentScore) return;
    
    try {
      setLoading(true);
      
      // 计算总积分
      const totalScore = calculateTotalScore(form);
      // 计算评价等级（处分）
      const evaluation = calculateEvaluation(totalScore);
      
      // 创建更新的积分记录
      const updatedScore: ComprehensiveScore = {
        id: currentScore.id,
        studentId: form.studentId,
        studentName: form.studentName,
        semester: form.semester,
        baseScore: 80, // 默认基础分
        bonusScore: parseFloat(form.bonusScore || '0'),
        bonusReason: form.bonusReason || '',
        penaltyScore: parseFloat(form.penaltyScore || '0'),
        penaltyReason: form.penaltyReason || '',
        totalScore,
        evaluation,
        updateDate: form.updateDate
      };
      
      // 保存到localStorage
      const savedScores = JSON.parse(localStorage.getItem('comprehensiveScores') || '[]');
      const updatedScores = savedScores.map((s: ComprehensiveScore) =>
        s.id === currentScore.id ? updatedScore : s
      );
      localStorage.setItem('comprehensiveScores', JSON.stringify(updatedScores));
      
      // 更新学生数据中的score字段以保持同步
      const students = JSON.parse(localStorage.getItem('students') || JSON.stringify(mockStudents));
      const updatedStudents = students.map((s: Student) => 
        s.studentId === form.studentId ? { ...s, score: totalScore.toString() } : s
      );
      localStorage.setItem('students', JSON.stringify(updatedStudents));
      
      // 重新加载数据以更新UI
      await loadScores();
      setIsEditOpen(false);
      setAlert('编辑综合积分成功');
      setShowAlert(true);
    } catch (error) {
      console.error('编辑综合积分失败:', error);
      setAlert('编辑综合积分失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 处理删除综合积分
  const handleDelete = async () => {
    if (!currentScore) return;
    try {
      setLoading(true);
      
      // 从localStorage删除记录
      const savedScores = JSON.parse(localStorage.getItem('comprehensiveScores') || '[]');
      const updatedScores = savedScores.filter((s: ComprehensiveScore) => s.id !== currentScore.id);
      localStorage.setItem('comprehensiveScores', JSON.stringify(updatedScores));
      
      // 更新学生数据中的score字段以保持同步（将其设为默认值）
      const students = JSON.parse(localStorage.getItem('students') || JSON.stringify(mockStudents));
      const updatedStudents = students.map((s: Student) => 
        s.studentId === currentScore.studentId ? { ...s, score: '' } : s
      );
      localStorage.setItem('students', JSON.stringify(updatedStudents));
      
      // 重新加载数据以更新UI
      await loadScores();
      setIsDeleteOpen(false);
      setAlert('删除综合积分成功');
      setShowAlert(true);
    } catch (error) {
      console.error('删除综合积分失败:', error);
      setAlert('删除综合积分失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      studentId: '',
      studentName: '',
      semester: '',
      bonusScore: '',
      bonusReason: '',
      penaltyScore: '',
      penaltyReason: '',
      updateDate: new Date().toISOString().split('T')[0],
    });
    setCurrentScore(null);
  };

  // 过滤综合积分列表
  const filteredScores = scores.filter(score => {
    const matchesSearch = 
      score.studentName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      score.studentId.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (score.bonusReason && score.bonusReason.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (score.penaltyReason && score.penaltyReason.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesSemester = selectedSemester === 'all' || score.semester === selectedSemester;
    return matchesSearch && matchesSemester;
  });

  // 统计信息
  const statistics = {
    total: scores.length,
    excellent: scores.filter(s => s.evaluation === '优秀').length,
    good: scores.filter(s => s.evaluation === '良好').length,
    medium: scores.filter(s => s.evaluation === '中等').length,
    pass: scores.filter(s => s.evaluation === '及格').length,
    fail: scores.filter(s => s.evaluation === '不及格').length,
    averageTotalScore: scores.length > 0 
      ? (scores.reduce((sum, score) => sum + score.totalScore, 0) / scores.length).toFixed(2) 
      : 0
  };

  // 根据评价等级获取颜色
  const getEvaluationColor = (evaluation: string) => {
    switch(evaluation) {
      case '优秀': return 'text-green-600';
      case '良好': return 'text-blue-600';
      case '中等': return 'text-yellow-600';
      case '及格': return 'text-orange-600';
      case '不及格': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <Text className="text-2xl font-bold text-gray-900">操行积分管理</Text>
        <div className="flex items-center gap-3">
          <div className="relative">
            <Input
              type="text"
              placeholder="搜索学生姓名、学号或备注..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">🔍</span>
          </div>
          <div className="relative">
            <select
              value={selectedSemester}
              onChange={(e) => setSelectedSemester(e.target.value)}
              className="w-[180px] px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white appearance-none"
            >
              {semesters.map(semester => (
                <option key={semester} value={semester}>
                  {semester === 'all' ? '全部学期' : semester}
                </option>
              ))}
            </select>
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
              <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                <path d="M7 10l5 5 5-5z"/>
              </svg>
            </div>
          </div>
          {canAdd && (
            <Button variant="primary" onClick={handleAddOpen}>
              添加积分记录
            </Button>
          )}
        </div>
      </div>

      {/* 统计信息 */}
      <div className="bg-blue-50 p-4 rounded-md mb-6">
        <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
          <div className="text-center">
            <Text className="text-blue-700 text-sm">总人数</Text>
            <Text className="text-xl font-bold text-blue-800">{statistics.total}</Text>
          </div>
          <div className="text-center">
            <Text className="text-blue-700 text-sm">平均分</Text>
            <Text className="text-xl font-bold text-blue-800">{statistics.averageTotalScore}</Text>
          </div>
          <div className="text-center">
            <Text className="text-blue-700 text-sm">优秀</Text>
            <Text className={`text-xl font-bold ${getEvaluationColor('优秀')}`}>{statistics.excellent}</Text>
          </div>
          <div className="text-center">
            <Text className="text-blue-700 text-sm">良好</Text>
            <Text className={`text-xl font-bold ${getEvaluationColor('良好')}`}>{statistics.good}</Text>
          </div>
          <div className="text-center">
            <Text className="text-blue-700 text-sm">记过</Text>
            <Text className={`text-xl font-bold ${getEvaluationColor('记过')}`}>{statistics.memo}</Text>
          </div>
          <div className="text-center">
            <Text className="text-blue-700 text-sm">警告</Text>
            <Text className={`text-xl font-bold ${getEvaluationColor('严重警告')}`}>{statistics.warning}</Text>
          </div>
        </div>
      </div>

      {/* 警告提示 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md relative">
          <Text className="text-blue-700">{alert}</Text>
          <Button 
            variant="ghost"
            size="sm" 
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}

      {/* 综合积分列表表格 */}
      <div className="overflow-x-auto">
        <Table>
            <TableHeader>
              <TableRow>
                <TableHead>学生姓名</TableHead>
                <TableHead>综合积分</TableHead>
                <TableHead>扣分项</TableHead>
                <TableHead>加分项</TableHead>
                <TableHead>更新日期</TableHead>
                <TableHead>处分</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    <Spinner className="mx-auto" />
                  </TableCell>
                </TableRow>
              ) : filteredScores.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    暂无综合积分数据
                  </TableCell>
                </TableRow>
              ) : (
                filteredScores.map((score) => (
                  <TableRow key={score.id}>
                    <TableCell>{score.studentName}</TableCell>
                    <TableCell className="font-bold">{score.totalScore}</TableCell>
                    <TableCell>
                      <div>-{score.penaltyScore}</div>
                      <div className="text-xs text-gray-500">{score.penaltyReason || '无'}</div>
                    </TableCell>
                    <TableCell>
                      <div className="text-green-600">+{score.bonusScore}</div>
                      <div className="text-xs text-gray-500">{score.bonusReason || '无'}</div>
                    </TableCell>
                    <TableCell>{score.updateDate}</TableCell>
                    <TableCell>
                      <span className={`font-bold ${getEvaluationColor(score.evaluation)}`}>
                        {score.evaluation}
                      </span>
                    </TableCell>
                    <TableCell>
                      {canDelete && (
                        <Button variant="ghost" color="red" onClick={() => handleDeleteOpen(score)}>
                          删除
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
      </div>

      {/* 添加综合积分对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>添加综合积分</DialogTitle>
            <DialogDescription>
              请填写综合积分信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="studentId" className="text-right">学号</Label>
              <Input
                id="studentId"
                name="studentId"
                value={form.studentId}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="studentName" className="text-right">学生姓名</Label>
              <Input
                id="studentName"
                name="studentName"
                value={form.studentName}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="semester" className="text-right">学期</Label>
              <Input
                id="semester"
                name="semester"
                value={form.semester}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="bonusScore" className="text-right">加分项</Label>
              <Input
                id="bonusScore"
                name="bonusScore"
                type="number"
                min="0"
                max="50"
                value={form.bonusScore}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-start gap-4">
              <Label htmlFor="bonusReason" className="text-right pt-2">加分原因</Label>
              <Input
                id="bonusReason"
                name="bonusReason"
                type="text"
                value={form.bonusReason}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="penaltyScore" className="text-right">减分项</Label>
              <Input
                id="penaltyScore"
                name="penaltyScore"
                type="number"
                min="0"
                max="50"
                value={form.penaltyScore}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-start gap-4">
              <Label htmlFor="penaltyReason" className="text-right pt-2">扣分原因</Label>
              <Input
                id="penaltyReason"
                name="penaltyReason"
                type="text"
                value={form.penaltyReason}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="updateDate" className="text-right">更新日期</Label>
              <Input
                id="updateDate"
                name="updateDate"
                type="date"
                value={form.updateDate}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>添加</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑综合积分对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>编辑综合积分</DialogTitle>
            <DialogDescription>
              请修改综合积分信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-studentId" className="text-right">学号</Label>
              <Input
                id="edit-studentId"
                name="studentId"
                value={form.studentId}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-studentName" className="text-right">学生姓名</Label>
              <Input
                id="edit-studentName"
                name="studentName"
                value={form.studentName}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-semester" className="text-right">学期</Label>
              <Input
                id="edit-semester"
                name="semester"
                value={form.semester}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-bonusScore" className="text-right">加分项</Label>
              <Input
                id="edit-bonusScore"
                name="bonusScore"
                type="number"
                min="0"
                max="50"
                value={form.bonusScore}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-start gap-4">
              <Label htmlFor="edit-bonusReason" className="text-right pt-2">加分原因</Label>
              <Input
                id="edit-bonusReason"
                name="bonusReason"
                type="text"
                value={form.bonusReason}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-penaltyScore" className="text-right">减分项</Label>
              <Input
                id="edit-penaltyScore"
                name="penaltyScore"
                type="number"
                min="0"
                max="50"
                value={form.penaltyScore}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-start gap-4">
              <Label htmlFor="edit-penaltyReason" className="text-right pt-2">扣分原因</Label>
              <Input
                id="edit-penaltyReason"
                name="penaltyReason"
                type="text"
                value={form.penaltyReason}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-updateDate" className="text-right">更新日期</Label>
              <Input
                id="edit-updateDate"
                name="updateDate"
                type="date"
                value={form.updateDate}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleEdit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除综合积分对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除综合积分记录</DialogTitle>
            <DialogDescription>
              确定要删除这条综合积分记录吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          {currentScore && (
            <div className="py-4">
              <Text>学生姓名：{currentScore.studentName}</Text>
              <Text>学号：{currentScore.studentId}</Text>
              <Text>学期：{currentScore.semester}</Text>
              <Text>总积分：{currentScore.totalScore}</Text>
              <Text>评价等级：{currentScore.evaluation}</Text>
            </div>
          )}
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button  variant="ghost" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}